package com.chalmers.foa.gamemodel.gameobjects.switches.impl;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;

import com.chalmers.foa.gamemodel.events.IEvent;
import com.chalmers.foa.gamemodel.gameobjects.GameObjectBitmapAdapter;
import com.chalmers.foa.gamemodel.gameobjects.switches.ISwitch;

public class LeverSwitch extends GameObjectBitmapAdapter implements ISwitch {

	private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
	private Bitmap orgBitmap, switchActivated;
	private IEvent event;
	
	private boolean switched;
	
	public LeverSwitch(Point position, Bitmap bitmap,int layer,int bound) {
		super(bitmap, position,layer,bound);
		orgBitmap = Bitmap.createBitmap(getBitmap());
		initBitmaps();
		switched = false;
	}
	
	public LeverSwitch(Bitmap bitmap) {
		this( new Point(0,0),bitmap,0,-1);
	}
	
	private void initBitmaps() {
		Matrix scaleMatrix = new Matrix();
		int xScale = 1, yScale = 1;
		
		xScale = -1;
		yScale = 1;
		scaleMatrix.postScale(xScale, yScale); 
		switchActivated = Bitmap.createBitmap(orgBitmap, 0, 0, 
                width, height, scaleMatrix, true);
	}
	
	public boolean isSwitched() {
		return switched;
	}

	public void setSwitched() {
		triggerEvent();
		revert();
		if(switched)
			bitmap = switchActivated;
		else
			bitmap = orgBitmap;
	}
	public void revert(){
		switched=!switched;
	}
	@Override
	public void revertToStartPosition(){
		super.revertToStartPosition();
		bitmap = orgBitmap;
		switched=false;
	}

	@Override
	public void addPropertyChangeListener(PropertyChangeListener pcl) {
		pcs.addPropertyChangeListener(pcl);
	}

	@Override
	public void bindEvent(IEvent _event) {
		event=_event;
	}

	@Override
	public void triggerEvent() {
		pcs.firePropertyChange(new PropertyChangeEvent(this, "event", null, event));
	}

	@Override
	public boolean hasEvent() {
		return event!=null;
	}
}

